package com.yegs.jltqc.serviceImpl;

import com.yegs.jltqc.TO.NamePageQuery;
import com.yegs.jltqc.VO.Report;
import com.yegs.jltqc.common.StoreException;
import com.yegs.jltqc.config.ConcurentCache;
import com.yegs.jltqc.dao.ReportRepository;
import com.yegs.jltqc.service.ReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportRepository reportRepository;

    @Override
    public Report save(Report report) {
         if(report.getId() == null){
             report.setCreateTime(new Date());
             report.setCreateBy(ConcurentCache.getUserName());
             report = reportRepository.save(report);
         }else{
             report.setUpdateBy(ConcurentCache.getUserName());
             report.setCreateTime(new Date());
             report = reportRepository.save(report);
         }
        return report;
    }

    @Override
    public List<Report> list() {
        return reportRepository.findAll();
    }

    @Override
    public Report get(Long id) {
        return reportRepository.getOne(id);
    }

    @Override
    public void del(Long id) {
        reportRepository.deleteById(id);
    }

    @Override
    public Page<Report> query(NamePageQuery query) {
        PageRequest request = PageRequest.of(query.getPageIndex() - 1, query.getPageSize());
        if(query.getName() == null || query.getName().trim() == ""){
            return reportRepository.findAll(request);
        }
        return reportRepository.findReportByName(query.getName(), request);
    }

    @Override
    public Long getNext(Long id, String mold) {
        if(id == null){
            Report outCome = reportRepository.findFirstByMoldOrderByIdDesc(mold);
            if(outCome != null) {
                return outCome.getId();
            }
        }
        else{
            Report outCome = reportRepository.findFirstByIdAfterAndMold(id, mold);
            if(outCome == null){ outCome = reportRepository.findFirstByMoldOrderByIdDesc(mold); }
            if(outCome != null){
                return outCome.getId();
            }
        }
        return null;
    }

    @Override
    public Long getLast(Long id, String mold) {
        if(id == null){
            Report outCome = reportRepository.findFirstByMoldOrderByIdDesc(mold);
            if(outCome != null) {
                return outCome.getId();
            }
        }
        else{
            Report outCome = reportRepository.findFirstByIdBeforeAndMoldOrderByIdDesc(id, mold);
            if(outCome == null){ outCome = reportRepository.findFirstByMoldOrderById(mold); }
            if(outCome != null){
                return outCome.getId();
            }
        }
        return null;
    }
}
